//
//  SYComposeTextView+Extension.swift
//  YANAWeibo
//
//  Created by mac on 16/5/23.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

extension SYComposeTextView {
    
    var emoticonText: String {
        
        var result = ""
        attributedText.enumerateAttributesInRange(NSMakeRange(0, attributedText.length), options: []) { (infoDic, customRange, _) -> Void in
            if let attachment = infoDic["NSAttachment"] as? SYTextAttachment {
                let chs = attachment.emoticon!.chs!
                result += chs
            } else {
                // 文本
                let text = self.attributedText.attributedSubstringFromRange(customRange).string
                result += text
            }
        }
        return result
    }
    

    func insertEmoticon(emoticon: SYEmoticon, font: UIFont) {
        
        // 判断表情类型
        if emoticon.type == "0" {
            // 记录上一次的富文本
            let originalAttr = NSMutableAttributedString(attributedString: self.attributedText)
            
            // 1.获取图片
            let image = UIImage(named: emoticon.path!)
            
            // 2.创建NSTextAttachment
            let attachment = SYTextAttachment()
            // 设置模型
            attachment.emoticon = emoticon
            attachment.image = image
            // 取到字体的高度
            let fontHeight = font.lineHeight
            attachment.bounds = CGRect(x: 0, y: -4, width: fontHeight, height: fontHeight)
            
            // 3.将Attachment包装成富文本
            let attr = NSAttributedString(attachment: attachment)
            
            // 获取textview的选中范围
            var range = selectedRange
            // 替换选中的字符串
            originalAttr.replaceCharactersInRange(range, withAttributedString: attr)
            
            // 4.显示富文本
            // 设置富文本的字体大小
            originalAttr.addAttribute(NSFontAttributeName, value: font, range: NSMakeRange(0, originalAttr.length))
            // 设置富文本
            self.attributedText = originalAttr
            
            range.location += 1
            range.length = 0
            // 设置选中范围
            selectedRange = range
            
            // 发送改变文字的通知
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
//            delegate?.textViewDidChange?(self)
            
        } else {
            self.insertText(emoticon.code!.changeStrToEmoji())
        }
    
    }
}
